package cn.good.yan.controller;

import cn.good.yan.mapper.BillMapper;
import cn.good.yan.pojo.Bill;
import cn.good.yan.resp.ResultData;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Enumeration;

/**
 * 演示 Gateway 网关
 *
 * @author shengren.yan
 * @create 2024-05-04
 */
@RestController
public class PayGateWayController {
    @Resource
    BillMapper billMapper;

    /**
     * 测试 Gateway - 网关的访问
     *
     * @param id
     * @return {@link ResultData}<{@link Bill}>
     */
    @GetMapping(value = "/g/gateway/get/{id}")
    public ResultData<Bill> getById(@PathVariable("id") Long id) {
        Bill pay = billMapper.findByBid(id).get(0);
        return ResultData.success(pay);
    }

    /**
     * 测试 Gateway - 网关的断言
     *
     * @return {@link ResultData}<{@link String}>
     */
    @GetMapping(value = "/g/gateway/info")
    public ResultData<String> getGatewayInfo() {
        return ResultData.success("gateway 请求：" + IdUtil.simpleUUID());
    }


    /**
     * 测试 Gateway - 网关的过滤器
     *
     * @return {@link ResultData}<{@link String}>
     */
    @GetMapping(value = "/g/gateway/filter")
    public ResultData<String> getGatewayFilter(HttpServletRequest request) {

        // 演示：消息头相关
        String result = "";
        // 获取消息头
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headName = headers.nextElement();
            String headValue = request.getHeader(headName);
            System.out.println("请求头名: " + headName + "---" + "请求头值: " + headValue);

            if (headName.equalsIgnoreCase("X-Request-yy1")
                    || headName.equalsIgnoreCase("X-Request-yy2")) {
                // 获取这2个请求头里的值， headName 请求头 、 headValue 请求头值
                result = result + headName + "请求头里的值= " + headValue + " ";
            }
        }

        // 演示：请求参数相关
        // 访问：http://localhost:9527/g/gateway/filter 接口 ，可以收到参数：cust的值是1001，参数：name接收不到
        // 访问：http://localhost:9527/g/gateway/filter?cust=555&name=200 接口 ，可以收到参数：cust的值是555，参数：name接收不到
        System.out.println("=============================================");
        String customerId = request.getParameter("cust");
        System.out.println("请求参数 cust 的值: " + customerId);

        String customerName = request.getParameter("name");
        System.out.println("请求参数 name 的值: " + customerName);
        System.out.println("=============================================");

        return ResultData.success("网关-过滤器 test： " + result + " \t " + DateUtil.now());
    }


}
